import React from 'react';

import path from '@/config/path';

/**
 * DashboardAuth decorator
 * @param Main Component
 * @return Component Class
 */
export default (Main) => {
    return class extends React.Component{
        componentDidMount(){ 
            if(!this.props.getUserInfo){
                throw new Error('please add @connect(state => state.user,{ getUserInfo }) on this decorator before.');
            }

            !this.props.userInfo.detail && this.props.getUserInfo();
        }
        
        componentWillReceiveProps(props, state){
            const { history, userInfo:user, match, location } = props;
            let PATHNAME = location.pathname;

            // redirectTo
            if(this.redirectTo !== props.redirectTo && props.redirectTo !== undefined){
                this.redirectTo = props.redirectTo;
                history.push(props.redirectTo);
            }

            if(PATHNAME.lastIndexOf("/") === PATHNAME.length - 1){
                PATHNAME = PATHNAME.substring(PATHNAME, PATHNAME.length - 1);
            }
            
            if(path['30002'] === PATHNAME){
                +user.userType === 1 ? history.push(`${match.path}${path['30006']}`) : history.push(`${match.path}${path['30005']}`);
            }

            if(PATHNAME.indexOf(path['30006']) > -1 && +user.userType === 0){
                history.push(`${match.path}${path['30005']}`);
            } else if(PATHNAME.indexOf(path['30005']) > -1 && +user.userType === 1){
                history.push(`${match.path}${path['30006']}`);
            }
            
            if((PATHNAME.indexOf(path['30006']) > -1 || PATHNAME.indexOf(path['30005']) > -1) && user.detail && !user.detail.tx){
                history.push(`${match.path}${path['30004']}`);
            }
        }
        render(){
            return <Main {...this.props} />
        }
    }
}